﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using CrawlerCore;
using HtmlAgilityPack;

namespace WCrawlerLib
{
    public class BrowserSession_vBulletin4x : BrowserSession_vBulletin
    {
        public BrowserSession_vBulletin4x()
        {
            ForumTypeId = enumForumType.vBulletin4x;
        }

        ///// <summary>
        ///// var LOGGEDIN = 108592 > 0 ? true : false;
        ///// </summary>
        ///// <returns></returns>
        //public override int GetUserIdAfterLogin()
        //{
        //    int userId = -1;
        //    string pattern = @"var\sLOGGEDIN\s=\s(?<userId>([0-9]+))";
        //    Regex r = new Regex(pattern);
        //    Match m = r.Match(HtmlDoc.DocumentNode.InnerHtml);
        //    if (m.Success)
        //        userId = int.Parse(m.Result("${userId}"));
        //    return userId;
        //}

        /// <summary>
        /// Get threads with the indexes of paging
        /// </summary>
        /// <param name="forumUrl"></param>
        /// <param name="doc"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public override List<DataRow> SearchThreadsByPaging(string forumUrl, HtmlDocument doc, DataTable table)
        {
            List<DataRow> rowList = new List<DataRow>();
            //pattern get thread num
            string xPath = @".//li[contains(@id,'thread')]";
            HtmlNodeCollection nodeCollection = HtmlDoc.DocumentNode.SelectNodes(xPath);
            if (nodeCollection != null)
            {
                foreach (HtmlNode node in nodeCollection)
                {
                    DataRow row = table.NewRow();
                    //1. Get thread num
                    Regex r = new Regex("[0-9]+");
                    Match m = r.Match(node.Attributes["id"].Value);
                    if (m.Success)
                    {
                        row["ThreadNum"] = m.Value;
                        //2. Get title
                        xPath = ".//div[@class='threadinfo thread']//a[contains(@id,'thread_title')]";
                        HtmlNodeCollection node1 = node.SelectNodes(xPath);
                        string href = node1[0].Attributes["href"].Value;
                        row["Title"] = node1[0].InnerHtml;
                        row["Url"] = GeneralClass.GetFullUrl(forumUrl, href);

                        //3. Get Replies and Views
                        xPath = ".//ul[@class='threadstats td alt']/li/text()";
                        node1 = node.SelectNodes(xPath);
                        //Get replies
                        m = r.Match(node1[0].InnerText);
                        if (m.Success)
                            row["Replies"] = m.Value;
                        else
                            row["Replies"] = "0";
                        //Get views
                        m = r.Match(node1[1].InnerText);
                        if (m.Success)
                            row["Views"] = m.Value;
                        else
                            row["Views"] = "0";

                        //4. Get Forum
                        xPath = ".//div[@class='threadpostedin td alt']//a";
                        node1 = node.SelectNodes(xPath);
                        href = node1[0].Attributes["href"].Value;
                        row["Forum"] = node1[0].OuterHtml.Replace(href, forumUrl + "/" + href);

                        //Get post num
                        //row["PostNum"] = GetPostNum(row["Url"].ToString());

                        rowList.Add(row);
                    }
                }
            }
            return rowList;
        }



        /// <summary>
        /// Search thread num and post num in a thread page
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public override string[] GetThreadPostNum(HtmlDocument doc)//(string threadUrl)
        {
            //HtmlDocument doc = Get(threadUrl);
            string[] result = new string[2];

            if (doc != null)
            {
                //Find thread num
                //newreply.php?do=postreply&t=3502709
                string xPath = ".//form[contains(@action,'newreply')]";
                //string xPath = ".//form[contains(@action,'newreply')]"; 3x
                HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(xPath);
                if (nodeCollection != null)
                {
                    string replyUrl = nodeCollection[0].Attributes["action"].Value.Replace("postcount", "");
                    Regex r = new Regex(@"newreply\.php\?do=postreply(\&|\&amp\;)t=(?<threadnum>[0-9]+)");
                    //Regex r = new Regex(@"newreply\.php\?do=postreply(\&|\&amp\;)t=(?<threadnum>[0-9]+)"); 3x
                    Match m = r.Match(replyUrl);
                    if (m.Success)
                    {
                        result[0] = m.Result("${threadnum}");
                    }
                }

                //Find first post num
                xPath = ".//a[@class='postcounter' and text()='#1']";
                //xPath = ".//a[starts-with(@id,'postcount') and substring-after(@id, 'postcount') >= 0]"; 3x
                nodeCollection = doc.DocumentNode.SelectNodes(xPath);
                if (nodeCollection != null)
                    result[1] = nodeCollection[0].Attributes["name"].Value.Replace("post", "");
            }
            return result;
        }

        public override bool PostReply(string topicUrl, string forumUrl, string message)
        {
            throw new NotImplementedException();
        }
    }
}